﻿using Microsoft.AspNetCore.Mvc;
using wx.web.Interface;

namespace wx.web.Controllers
{
    public class WeChatController : Controller
    {
        private readonly IWeChatService _weChatService;
        private readonly ILogger<WeChatController> _logger;

        public WeChatController(IWeChatService weChatService, ILogger<WeChatController> logger)
        {
            _weChatService = weChatService;
            _logger = logger;
        }

        /// <summary>
        /// 微信服务器验证（GET请求）
        /// </summary>
        [HttpGet]
        public IActionResult Validate([FromQuery] string signature, [FromQuery] string timestamp, [FromQuery] string nonce, [FromQuery] string echostr)
        {
            _logger.LogInformation($"微信验证请求: signature={signature}, timestamp={timestamp}, nonce={nonce}, echostr={echostr}");

            if (_weChatService.ValidateSignature(signature, timestamp, nonce))
            {
                _logger.LogInformation("微信签名验证成功");
                return Content(echostr);
            }

            _logger.LogWarning("微信签名验证失败");
            return Content("签名验证失败");
        }

        /// <summary>
        /// 发起微信授权（静默授权，只获取openid）
        /// </summary>
        [HttpGet("authorize")]
        public IActionResult Authorize([FromQuery] string returnUrl = "")
        {
            try
            {
                if (string.IsNullOrEmpty(returnUrl))
                    returnUrl = Url.Action("Index", "Home", null, Request.Scheme)!;

                // 生成回调URL
                var callbackUrl = Url.Action("Callback", "WeChat", null, Request.Scheme)!;

                // 生成state参数（防CSRF攻击）
                var state = Guid.NewGuid().ToString("N");
                HttpContext.Session.SetString("wechat_state", state);
                HttpContext.Session.SetString("wechat_return_url", returnUrl);

                var authUrl = _weChatService.GenerateAuthorizationUrl(callbackUrl, "snsapi_base", state);

                _logger.LogInformation($"生成授权URL: {authUrl}");

                return Redirect(authUrl);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成授权URL失败");
                return BadRequest($"授权失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发起微信授权（获取用户信息）
        /// </summary>
        [HttpGet("authorize-userinfo")]
        public IActionResult AuthorizeUserInfo([FromQuery] string returnUrl = "")
        {
            try
            {
                if (string.IsNullOrEmpty(returnUrl))
                    returnUrl = Url.Action("Profile", "Home", null, Request.Scheme)!;

                var callbackUrl = Url.Action("Callback", "WeChat", null, Request.Scheme)!;

                var state = Guid.NewGuid().ToString("N");
                HttpContext.Session.SetString("wechat_state", state);
                HttpContext.Session.SetString("wechat_return_url", returnUrl);
                HttpContext.Session.SetString("wechat_scope", "snsapi_userinfo");

                var authUrl = _weChatService.GenerateAuthorizationUrl(callbackUrl, "snsapi_userinfo", state);

                _logger.LogInformation($"生成用户信息授权URL: {authUrl}");

                return Redirect(authUrl);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成用户信息授权URL失败");
                return BadRequest($"授权失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 微信授权回调处理
        /// </summary>
        [HttpGet("callback")]
        public async Task<IActionResult> Callback([FromQuery] string code, [FromQuery] string state)
        {
            try
            {
                _logger.LogInformation($"微信回调: code={code}, state={state}");

                // 验证state参数
                var savedState = HttpContext.Session.GetString("wechat_state");
                if (state != savedState)
                {
                    _logger.LogWarning($"State验证失败: 请求state={state}, 保存state={savedState}");
                    return BadRequest("非法请求：state参数验证失败");
                }

                if (string.IsNullOrEmpty(code))
                {
                    _logger.LogWarning("未收到code参数");
                    return BadRequest("授权失败：未获取到授权码");
                }

                // 获取access_token和openid
                var tokenResult = await _weChatService.GetAccessTokenAsync(code);

                if (tokenResult == null || string.IsNullOrEmpty(tokenResult.OpenId))
                {
                    _logger.LogError("获取access_token失败");
                    return BadRequest("授权失败：无法获取用户信息");
                }

                // 存储基础信息到Session
                HttpContext.Session.SetString("wechat_openid", tokenResult.OpenId);
                HttpContext.Session.SetString("wechat_access_token", tokenResult.AccessToken);
                HttpContext.Session.SetString("wechat_scope", tokenResult.Scope);

                _logger.LogInformation($"用户授权成功: OpenId={tokenResult.OpenId}, Scope={tokenResult.Scope}");

                // 如果是用户信息授权，获取详细信息
                if (tokenResult.Scope == "snsapi_userinfo")
                {
                    var userInfo = await _weChatService.GetUserInfoAsync(tokenResult.AccessToken!, tokenResult.OpenId);
                    if (userInfo != null)
                    {
                        HttpContext.Session.SetString("wechat_nickname", userInfo.Nickname ?? "");
                        HttpContext.Session.SetString("wechat_headimgurl", userInfo.HeadImgUrl ?? "");
                        HttpContext.Session.SetString("wechat_unionid", userInfo.UnionId ?? "");

                        _logger.LogInformation($"获取用户信息成功: Nickname={userInfo.Nickname}");
                    }
                }

                // 清理临时状态
                HttpContext.Session.Remove("wechat_state");

                // 获取返回URL并重定向
                var returnUrl = HttpContext.Session.GetString("wechat_return_url");
                if (string.IsNullOrEmpty(returnUrl))
                    returnUrl = Url.Action("Index", "Home", null, Request.Scheme)!;

                HttpContext.Session.Remove("wechat_return_url");

                _logger.LogInformation($"授权完成，重定向到: {returnUrl}");

                return Redirect(returnUrl);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "微信授权回调处理失败");
                return BadRequest($"授权处理失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        [HttpGet("userinfo")]
        public IActionResult GetUserInfo()
        {
            var openId = HttpContext.Session.GetString("wechat_openid");
            if (string.IsNullOrEmpty(openId))
            {
                return Unauthorized(new { success = false, message = "用户未登录" });
            }

            var userInfo = new
            {
                OpenId = openId,
                Nickname = HttpContext.Session.GetString("wechat_nickname"),
                HeadImgUrl = HttpContext.Session.GetString("wechat_headimgurl"),
                UnionId = HttpContext.Session.GetString("wechat_unionid"),
                Scope = HttpContext.Session.GetString("wechat_scope")
            };

            return Ok(new { success = true, data = userInfo });
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        [HttpPost("logout")]
        public IActionResult Logout()
        {
            HttpContext.Session.Remove("wechat_openid");
            HttpContext.Session.Remove("wechat_access_token");
            HttpContext.Session.Remove("wechat_nickname");
            HttpContext.Session.Remove("wechat_headimgurl");
            HttpContext.Session.Remove("wechat_unionid");
            HttpContext.Session.Remove("wechat_scope");

            _logger.LogInformation("用户退出登录");

            return Ok(new { success = true, message = "退出成功" });
        }
    }
}
